#import "AccountManager.h"
#import "YYModel.h"
#import "TimeBoat-Swift.h"

NSNotificationName const kUserDidLoginNotification = @"kUserDidLoginNotification";
NSNotificationName const kUserDidLogoutNotification = @"kUserDidLogoutNotification";
NSNotificationName const kUserDidUpdateNotification = @"kUserDidUpdateNotification";

NSNotificationName const kUserDeviceListUpdateNotification = @"kUserDeviceListUpdatNotification";
NSNotificationName const kUserDeviceListClearNotification = @"kUserDeviceListClearNotification";

static NSString *USER_DATA_KEY = @"user_info_v1";
static NSString *PROMPT_AGREEMENT_KEY = @"prompt_agreement_key";
static NSString *PROMPT_AGREEMENT_VALUE = @"1";

static NSString *USER_DEVICE_LIST_KEY = @"user_device_list_key_v1";

@interface AccountManager ()
/// 回调
@property (copy, nullable, nonatomic) AccountManagerLoginCompletion callback;

@end

@implementation AccountManager

+ (AccountManager *)shareAccount {
    static AccountManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    
    return manager;
}

- (instancetype)init {
    self = [super init];
    [self loadData];
    
    return self;
}

- (NSUserDefaults *)userDefaults {
    return [NSUserDefaults standardUserDefaults];
}

- (NSNotificationCenter *)notificationCenter {
    return [NSNotificationCenter defaultCenter];
}

- (void)loadData {
    DMLog(@"load data");
    
    NSData *data = [[self userDefaults] dataForKey:USER_DATA_KEY];
    if (nil != data) {
        _loginModel = [LoginModel yy_modelWithJSON:data];
    }
    
    [self loadDeviceList];
}

- (void)storeData {
    if (nil != _loginModel) {
        NSData *data = [_loginModel yy_modelToJSONData];
        if (nil != data) {
            [[self userDefaults] setObject:data forKey:USER_DATA_KEY];
            [[self userDefaults] synchronize];
        }
    }
}

- (void)logout {
    DMLog(@"logout");
    
    _loginModel = nil;
    [[self userDefaults] removeObjectForKey:USER_DATA_KEY];
    [[self userDefaults] synchronize];
    
    [[self notificationCenter] postNotificationName:kUserDidLogoutNotification object:nil];
    
    [self clearDeviceList];
}

- (BOOL)didLogined {
    return _loginModel.token.length > 0;
}

- (nullable NSString *)token {
    return _loginModel.token;
}

- (nullable NSString *)userUUID {
    if (nil != _loginModel.userUUID) {
        return _loginModel.userUUID;
    }
    
    return @"";
}

- (void)login:(LoginModel *)model {
    if (nil != model) {
        _loginModel = model;
        
        [self storeData];

        [[self notificationCenter] postNotificationName:kUserDidLoginNotification object:_loginModel];
        [self callCallback];
    }
}

- (void)update:(LoginModel *)model {
    if (nil != model) {
        _loginModel = model;
        
        [self storeData];
        
        [[self notificationCenter] postNotificationName:kUserDidUpdateNotification object:_loginModel];
        [self callback];
    }
}

+ (void)loginIfNeed:(UIViewController *)from completion:(AccountManagerLoginCompletion)completion {
    [AccountManager shareAccount].callback = completion;
    
    if ([AccountManager shareAccount].didLogined) {
        [[AccountManager shareAccount] callCallback];
    } else {
        LoginViewController *loginCtr = [[LoginViewController alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginCtr];
        nav.modalPresentationStyle = UIModalPresentationFullScreen;
        [from presentViewController:nav animated:YES completion:nil];
    }
}

- (void)callCallback {
    if (self.callback != nil) {
        self.callback(self.didLogined, _loginModel);
    }
    
    self.callback = nil;
}

- (BOOL)needPromptAgreement {
    return ![[[self userDefaults] stringForKey:PROMPT_AGREEMENT_KEY] isEqualToString:@"1"] ;
}

- (void)clearPromptAgreement {
    [[self userDefaults] setObject:PROMPT_AGREEMENT_VALUE forKey:PROMPT_AGREEMENT_KEY];
    [[self userDefaults] synchronize];
}


/// 保存用户设备列表
- (void)saveDeviceList:(NSArray<DeviceListItem *> *)list {
    if (nil != list) {
        _deviceList = list;
        NSString *str = [list yy_modelToJSONString];
        [[self userDefaults] setObject:str forKey:USER_DEVICE_LIST_KEY];
        [[self userDefaults] synchronize];
        
        [[self notificationCenter] postNotificationName:kUserDeviceListUpdateNotification object:_deviceList];
    }
}

- (void)loadDeviceList {
    NSString *json = [[self userDefaults] stringForKey:USER_DEVICE_LIST_KEY];
    if (nil != json && json.length > 0) {
        NSArray<DeviceListItem *> *list = [NSArray yy_modelArrayWithClass:DeviceListItem.class json:json];
        
        _deviceList = list;
    }
}

/// 清除用户设备列表
- (void)clearDeviceList {
    DMLog(@"clear device list");
    
    _deviceList = [NSMutableArray array];
    [[self userDefaults] removeObjectForKey:USER_DEVICE_LIST_KEY];
    [[self userDefaults] synchronize];
    [[self notificationCenter] postNotificationName:kUserDeviceListClearNotification object:nil];
}

/// 获取用户IMEI号
- (NSString *)deviceImei {
    if (nil != _deviceList && _deviceList.count > 0) {
        return _deviceList[0].imei;
    }
    
    return @"";
}

/// 获取设备MAC地址
- (NSString *)deviceMac {
    if (nil != _deviceList && _deviceList.count > 0) {
        return _deviceList[0].mac;
    }
    
    return @"";
}

@end
